home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 9720 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.3 KB

  1. Path: news-m01.ny.us.ibm.net!usenet
  2. From: rwolf@ibm.net
  3. Newsgroups: comp.lang.c++,rb.technical
  4. Subject: Re: Can copy constructor and operator= share code?
  5. Date: 4 Mar 1996 02:26:59 GMT
  6. Organization: Rudolph Research
  7. Message-ID: <4hdkdj$3id0@news-s01.ny.us.ibm.net>
  8. References: <4h2kcn$40d@rap.SanDiegoCA.ATTGIS.COM> <VA.00000053.00cdab05@fred>
  9. Reply-To: rwolf@ibm.net
  10. NNTP-Posting-Host: slip166-72-132-106.tx.us.ibm.net
  11. X-Newsreader: IBM NewsReader/2 v1.2
  12.  
  13. In <VA.00000053.00cdab05@fred>, Frederic LACHASSE <lachass@worldnet.fr> writes:
  14. >In article <4h2kcn$40d@rap.SanDiegoCA.ATTGIS.COM>, borisb@sd.znet.com 
  15. >(Boris Burtin) wrote:
  16. >> 
  17. >> I have noticed that a copy constructor and operator= perform pretty
  18. >> much the same function.  The code I wrote for my class simply copies
  19. >> each member variable from one class to the other.
  20. >> 
  21.  
  22. A rather typical form is to have the create a "ShallowCopy" 
  23. function that is called from both the copy constructor and the 
  24. operator=.   ShallowCopy copies only the member variables 
  25. at the current derivation level.
  26.  
  27. T::T(const T& t)
  28. {
  29.  ShallowCopy(t);
  30. }
  31.  
  32. T& operator=(const T& t )
  33. {
  34.    if (&t!=this)
  35.      {
  36.         ClassReset(); // direct destructor calls are bad form
  37.         ShallowCopy(t);
  38.         parentclass::operator=(t);
  39.  
  40.      }
  41. return *this;
  42. }
  43.  
  44.  
  45. If this form is followed at each level of derivation it will do what you want.
  46.